// router/index.js
import { createRouter, createWebHistory } from 'vue-router'


// 系统路由
const routes = [
    {
        path: '/',
        redirect: '/index'
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('../views/login.vue'),
        meta: {
            title: '登录',
            requiresAuth: false
        }
    },
    {
        path: '/index',
        name: 'Index',
        component: () => import('../views/index.vue'),
        meta: {
            title: '首页',
            requiresAuth: true
        }
    },
    {
        path: '/page1',
        name: 'Page1',
        component: () => import('../views/page/page1.vue'),
        meta: {
            title: '页面1',
            requiresAuth: true
        },
        children: [
            {
                path: 'page3',
                name: 'Page3',
                component: () => import('../views/page/page3.vue'),
                meta: {
                    title: '页面3',
                    requiresAuth: true
                }
            },
            {
                path: 'page4',
                name: 'Page4',
                component: () => import('../views/page/page4.vue'),
                meta: {
                    title: '页面4',
                    requiresAuth: true
                }
            }
        ]
    },
    // ... 其他路由配置
    
    // 添加404路由
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('../views/404.vue'),
        meta: {
            title: '404',
            requiresAuth: false
        }
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL), // 修正环境变量名称
    routes,
    scrollBehavior(to, from, savedPosition) {
        // 页面切换时滚动到顶部
        return savedPosition || { top: 0 }
    }
})

// 简化的路由守卫
router.beforeEach((to, from, next) => {
    // 设置页面标题
    document.title = to.meta.title || '默认标题'
    
    const isLoggedIn = !!localStorage.getItem('login_account')
    
    if (to.meta.requiresAuth && !isLoggedIn) {
        next({ 
            path: '/login', 
            query: { redirect: to.fullPath }
        })
    } else if (to.path === '/login' && isLoggedIn) {
        next({ path: '/' })
    } else {
        next()
    }
})

// 动态添加路由的函数
const addRoute = (route) => {
    try {
        router.addRoute(route)
        return true
    } catch (error) {
        console.error('添加路由失败:', error)
        return false
    }
}

export { router, addRoute }